package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"lx11/models"
	"path/filepath"
	"strings"
)

type BallController struct {
	beego.Controller
}
type Msg struct {
	Msg  string
	Code int
	Data interface{}
}

func (c *BallController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	//img := c.GetString("img")
	num, _ := c.GetInt("num")
	file, header, err := c.GetFile("img")
	if err != nil {
		res := Msg{
			Msg:  "请选择要上传的文件",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	ext := map[string]bool{
		".png": true,
		".jpg": true,
		"jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if ext[suffix] == false {
		res := Msg{
			Msg:  "图片格式不对",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	if header.Size > 2*1024*1024 {
		res := Msg{
			Msg:  "图片大于2mb",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	ball := models.Ball{
		Name:  name,
		Price: price,
		Img:   "http://127.0.0.1:8080/" + path,
		Num:   num,
	}
	err = models.DB.Debug().Create(&ball).Error
	if err != nil {
		res := Msg{
			Msg:  "添加失败",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Msg:  "添加成功",
			Code: 200,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *BallController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Ball{}, id).Error
	if err != nil {
		res := Msg{
			Msg:  "删除失败",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Msg:  "删除成功",
			Code: 200,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *BallController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	img := c.GetString("img")
	num, _ := c.GetInt("num")
	ball := models.Ball{
		Name:  name,
		Price: price,
		Img:   img,
		Num:   num,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&ball).Error
	if err != nil {
		res := Msg{
			Msg:  "修改失败",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Msg:  "修改成功",
			Code: 200,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *BallController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var alllist []models.Ball
	err := models.DB.Debug().Find(&alllist).Error
	if err != nil {
		res := Msg{
			Msg:  "查询失败",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Msg:  "查询成功",
			Code: 200,
			Data: alllist,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
